package com.testlayui.demo.controller;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.testlayui.demo.entity.Goods;
import com.testlayui.demo.service.GoodsService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

@RestController
@RequestMapping("/goods")
public class GoodsController {
    @Resource
    private GoodsService goodsService;

    @RequestMapping("/goodsList")
    public JSONObject getGoodList(@RequestParam("pageNum") int pageNum, @RequestParam("pageSize") int pageSize ){
        JSONObject result=new JSONObject();
        PageInfo<Goods> pageInfo=new PageInfo(goodsService.selectAll());
        System.out.println();
        result.put("code", "0");
        result.put("msg", "操作成功！");
        result.put("data", pageInfo.getList());
        result.put("count", pageInfo.getTotal());
        return result;
    }

    @RequestMapping(value = "/updateGood",method = RequestMethod.POST)
    public JSONObject updateGood(@RequestBody Goods goods){
        JSONObject result=new JSONObject();
        try {
            result.put("data",goodsService.update(goods));
            result.put("code", "0");
            result.put("msg", "操作成功！");
        }catch (Exception e)
        {
            result.put("code", "500");
            result.put("msg", "修改商品异常！");
            System.out.println(e.getMessage());
        }

        return result;
    }
    @RequestMapping(value = "/addGood", method = RequestMethod.POST)
    public  JSONObject addGood(@RequestBody Goods goods)
    {
        JSONObject result=new JSONObject();
        try{
            result.put("data",goodsService.insert(goods));
            result.put("code", "0");
            result.put("msg", "操作成功！");
        }catch (Exception e){
            result.put("code", "500");
            result.put("msg", "增加商品异常！");
            System.out.println(e.getMessage());
        }
        return  result;
    }
    @RequestMapping(value = "/deleteGood", method = RequestMethod.GET)
    public JSONObject deleteGood(@RequestParam("id") int id) {
        JSONObject result=new JSONObject();
        goodsService.deleteById(id);
        try {
            result.put("code", "0");
            result.put("msg", "操作成功！");
        }catch (Exception e){
            result.put("code", "500");
            result.put("msg", "删除商品异常！");
            System.out.println(e.getMessage());
        }
        return result;
    }
}
